<?php
/**
 * CRMLite Staff Model
 *
 * @final
 * @package        Crmlite_Model
 * @version        $Id: StaffModel.php 49 2007-09-06 07:17:07Z etng2004 $
 * @copyright      2006-2007 ETE.CN
 * @author         Yi BO  <etng2004@gmail.com>
 * @license        PHP Version 3.0 {@link http://www.php.net/license/3_0.txt}
 */


/**
 * 管理员表
 */
class Crmlite_Db_Table_Staff extends Crmlite_Db_Table {
	protected $_name = "staffs";
	protected $_primary = "id";
}

class StaffModel extends Crmlite_Model
{
	public function insert(&$record)
	{
		if(isset($record['userpass']))
		{
			$record['userpass'] = $this->hashPassword($record['userpass']);
		}
		return parent::insert($record);
	}

	public function update(&$record, $where =null)
	{
		if(isset($record['userpass']))
		{
			$record['userpass'] = $this->hashPassword($record['userpass']);
		}
		return parent::update($record, $where);
	}

	public function logout()
	{
		Zend_Session::forgetMe();
		Zend_Auth::getInstance()->clearIdentity();
		return true;
	}
	public function login($username, $userpass)
	{
		$ZendAuth = Zend_Auth::getInstance();
		$userpass = $this->hashPassword($userpass);
		$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Registry::get('db'), $this->dbt->getTable(), 'username', 'userpass', '?');
		$record = $_POST['fields'];
		$authAdapter->setIdentity($username)->setCredential($userpass);
		$result = $ZendAuth->authenticate($authAdapter);
		if($result->isValid())
		{
		    $staff_info = (array)$authAdapter->getResultRowObject(null, 'userpass');
		    switch ($staff_info['client_type'])
		    {
		    	case 'ALL':
		    		$staff_info['ROLE'] = 'ADMIN';
		    		break;
		    	case 'ADVERTISER':
		    		$staff_info['ROLE'] = 'ADVERTISER_STAFF';
		    		break;
		    	case 'PUBLISHER':
		    	    $staff_info['ROLE'] = 'PUBLISHER_STAFF';
		    	    break;
		    	default:
		    	    $staff_info['ROLE'] = 'GUEST';
		    		break;
		    }
			$ZendAuth->getStorage()->write($staff_info);
			return true;
		}
		$messages = array(
		1=>'SUCCESS',
		0=>'FAILURE',
		-1=>'FAILURE_IDENTITY_NOT_FOUND',
		-2=>'FAILURE_IDENTITY_AMBIGUOUS',
		-3=>'FAILURE_CREDENTIAL_INVALID',
		-4=>'FAILURE_UNCATEGORIZED'
		);
		$this->pushError('LOGIN', $messages[$result->getCode()]);
		return false;
	}
	protected function hashPassword($password)
	{
		return md5(md5($password));
	}
}